import { defineStore } from 'pinia'
import { getUser } from '@/api'
import { ElMessage } from 'element-plus'
import router from '@/routes'
import { bus } from '@/utils/eventBus'

export const useUserStore = defineStore('store', () => {
	const userInfo = ref({
		name: '',
		avatar: '',
		amount: 0,
	})

	const getUserInfo = async () => {
		const res = await getUser()

		if (res.code) return ElMessage.error('用户信息获取失败')
		Object.assign(userInfo.value, {
			name: res.name,
			avatar: res.avatar,
			amount: res.amount,
		})
	}

	const handleLogout = () => {
		Object.assign(userInfo.value, { name: '', avatar: '', amount: 0 })
		localStorage.removeItem('token')
		localStorage.removeItem('refresh_token')
	}

	return {
		userInfo,
		getUserInfo,
		handleLogout,
	}
})
